define('view/sys/role', ['WxCore',"vuex", 'text!./role.html'], function (wxCore,{ mapActions }, template) {

    return {
        template: template,
        data: function () {
            return {
                totalCount: 0,
                pageIndex:1,
                pageSize:10,
                tableData:[],
                columns:[
                    {
                        type: 'index',
                        title: '序号',
                        align: 'center',
                        width: 60
                    },
                    {
                        title: '角色名称',
                        key: 'roleName'
                    },
                    {
                        title: '更新时间',
                        key: 'updateTime'
                    },
                    {
                        title: '操作',
                        key: 'roleId',
                        align: 'center',
                        fixed: 'right',
                        width: 200,
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'default',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.editAction(params)
                                        }
                                    }}, '编辑'),
                                h('Button', {
                                    props: {
                                        type: 'default',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteAction(params)
                                        }
                                    }}, '删除'),
                                h('Button', {
                                    props: {
                                        type: 'default',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.authorizeAction(params)
                                        }
                                    }}, '授权')
                            ])
                        }
                    }
                ],
                loading:false,
                stripe:false,
                modalTitle:'',
                editModalShow:false,
                rolesLoaded:false,
                formRef: 'editForm',
                formData: {
                    roleName: '',
                    roleDescription: ''
                },
                formValidateRule: {},
                // 应用及资源
                userRoleSelected: {},
                clients: [],
                clientsLoaded: false,
                clientSelectedIndex: 0,
                clientSelected: {},
                resources: {},
                treeNodes: [],
                authoriseModal: false,
                authoriseModalTitle: '用户授权',
                authoriseContextTitle: '请选择授权',
                // 指定应用、角色的资源数组
                roleResources: []

            }
        },
        methods: {
            ...mapActions('UserRoleStore', [
                'getValidateRule','list', 'save', 'delete', 'listRoleResourcs', 'saveResources'
            ]),
            ...mapActions({
                loadClientAll: 'ClientStore/loadAll',
                loadClientResources: 'ResourceStore/listAll'
            }),
            onChangePage: function (currentPageIndex) {
                this.pageIndex = currentPageIndex;
                this.loadData();
            },
            loadClients: function () {
                return new Promise((resolve, reject) => {
                    if (!this.clientsLoaded) {
                        this.loadClientAll()
                            .then(Response => {
                                    this.clients = Response
                                    this.clientsLoaded = true
                                    this.$Message.info('加载应用信息成功')
                                    resolve()
                                },
                                (error) => {
                                    this.$Message.error('加载应用信息失败')
                                    reject(error)
                                })
                    } else {
                        resolve()
                    }
                })
            },
            loadData: function() {
                this.loading=true;
                this.list({
                    pageIndex:this.pageIndex,
                    pageSize:this.pageSize
                }).then((responseResult) => {
                    this.totalCount = responseResult.total;
                    this.tableData = responseResult.list.map((item, index) => {
                        let itemMap = wxCore.propertieToString(
                            item
                        )
                        return itemMap
                    })
                    this.loading = false;
                }).catch(err => {
                    console.log(err)
                    this.loading = false
                });
                //this.$emit('load-data', pageInfo)
            },
            // 打开新增窗口
            addAction: function () {
                this.clearFormData()
                this.formData = {};
                this.modalTitle = '新增角色'
                this.editModalShow = true
            },
            // 刷新列表
            refreshAction: function () {
                this.loadData();
            },
            formCancelHandle: function () {
                this.editModalShow = false
            },
            formSaveHandle: function () {
                this.$refs[this.formRef].validate(valid => {
                    if (!valid) {
                        this.$Message.error('输入信息不合法')
                    } else {
                        //console.log(this.formData);
                        const data = {
                            roleId: this.formData.roleId,
                            roleName: this.formData.roleName,
                            roleDescription: this.formData.roleDescription
                        }
                        this.save(this.formData)
                            .then(res => {
                                this.clearFormData();
                                this.editModalShow = false;
                                this.$Message.info('保存成功');
                                this.loadData();
                            })
                            .catch(err => {
                                this.$Message.error('登录帐户已经存在或服务异常');
                                console.log('>>>err:', err);
                            })
                    }
                });
            },
            clearFormData: function () {
                this.$refs[this.formRef].resetFields();
                this.formData = {};
            },
            editAction (params) {
                this.modalTitle = '角色编辑'
                this.editModalShow = true
                this.formData = {
                    roleId: params.row.roleId,
                    roleName: params.row.roleName,
                    roleDescription: params.row.roleDescription}
            },
            deleteAction (params) {
                this.$Modal.confirm({
                    title: '删除',
                    content: '确定要删除么？',
                    onOk: () => {
                        this.delete(params.row.roleId)
                            .then(res => {
                                this.$Message.info('删除成功')
                                this.loadData()
                            })
                            .catch(err => {
                                this.$Message.error(err)
                            })
                    }
                })

            },
            authorizeAction (params) {
                this.userRoleSelected = params.row
                // console.log('userRoleSelected', this.userRoleSelected)
                this.loadClients()
                    .then(() => {
                        return this.onclientSelected(0)
                    })
                this.authoriseModalTitle = '请为[' + params.row.roleName + ']角色授权'
                this.authoriseModal = true
            },
            deleteHandle: function (params) {
                this.delete(params.row.roleId).then(res => {
                    // console.log(res)
                    this.$Message.info('删除成功')
                    this.loadData()
                }).catch(() => {
                    // console.error(err)
                    this.$Message.error('删除失败')
                })
            },
            renderTreeNode (h, { root, node, data }) {
                // console.log('>>>', data)
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%'
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: 'ios-folder-outline'
                            },
                            style: {
                                marginRight: '8px'
                            }
                        }),
                        h('span', data.title)
                    ])
                ])
            },
            // 授权界面中应用选中事件处理
            onclientSelected (index) {
                // console.log(' select click', index)
                return new Promise((resolve, reject) => {
                    let oldSelectedItem = this.clients[this.clientSelectedIndex]
                    oldSelectedItem.selected = false
                    this.$set(this.clients, this.clientSelectedIndex, oldSelectedItem)

                    let selectedItem = this.clients[index]
                    selectedItem.selected = true
                    this.$set(this.clients, index, selectedItem)
                    this.clientSelectedIndex = parseInt(index)
                    this.clientSelected = this.clients[this.clientSelectedIndex]
                    this.treeNodes = []

                    let { roleId } = this.userRoleSelected
                    let { clientId } = this.clientSelected
                    // console.log('roleId:', roleId, 'clientId', clientId)
                    this.listRoleResourcs({roleId, clientId})
                        .then((Response) => {
                            this.roleResources = Response
                            return Promise.resolve()
                        }, (err) => {
                            reject(err)
                        })
                        .then(() => {
                            if (this.resources[this.clientSelected.clientId]) {
                                // console.log(this.resources[this.clientSelected.clientId])
                                let nodes = []
                                this.nodesBuild(nodes, ['', null])

                                this.treeNodes = nodes
                                resolve()
                            } else {
                                this.loadClientResources({ clientId: this.clientSelected.clientId })
                                    .then(Response => {
                                        this.resources[this.clientSelected.clientId] = Response

                                        let nodes = []
                                        this.nodesBuild(nodes, ['', null])
                                        this.treeNodes = nodes

                                        resolve()
                                    })
                            }
                        })
                })

                // 加载权限树数据
                // this.loadData()
                // console.log(this.getSelectedClientId())
            },
            nodesBuild: function (nodes, parentId) {
                for (let idx in this.resources[this.clientSelected.clientId]) {
                    let resource = this.resources[this.clientSelected.clientId][idx]
                    if (parentId.indexOf(resource.parentId) > -1) {
                        let node = {
                            nodeKey: resource.resourceId,
                            title: resource.resourceName,
                            clientId: resource.clientId,
                            resourceId: resource.resourceId,
                            resourceName: resource.resourceName,
                            parentId: resource.parentId,
                            url: resource.url,
                            permission: resource.permission,
                            orderValue: resource.orderValue,
                            expand: true,
                            children: []
                        }
                        let childs = this.resources[this.clientSelected.clientId].filter(res => {
                            return res.parentId === resource.resourceId
                        })
                        if (this.roleResources && this.roleResources instanceof Array && this.roleResources.indexOf(resource.resourceId) > -1 && childs.length < 1) {
                            node.checked = true
                        }
                        this.nodesBuild(node.children, [resource.resourceId])
                        nodes.push(node)
                    }
                }
            },
            saveAuthoriseHandle () {
                let checkedNodes = this.$refs['authoriseTree'].getCheckedNodes()
                // console.log(checkedNodes, this.userRoleSelected, this.clientSelected)
                let roleResource = {
                    clientId: this.clientSelected.clientId,
                    roleId: this.userRoleSelected.roleId,
                    resourceIds: []
                }
                for (let idx in checkedNodes) {
                    roleResource.resourceIds.push(checkedNodes[idx].resourceId)
                }
                // console.log(roleResource)
                this.saveResources(roleResource)
                    .then((Response) => {
                        this.authoriseModal = false
                        this.$Message.info('授权保存成功')
                    })
                    .catch(() => {
                        this.$Message.error('授权保存失败')
                    })
            }
        },
        created() {
            // 加载验证规则
            this.getValidateRule().then(val => {
                this.formValidateRule = {}
                for (let ruleColumn in val) {
                    this.formValidateRule[ruleColumn] = val[ruleColumn]
                }
            });
            this.loadData();
        }
    }
})